package com.example.c4;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author Jonathan
 * 2021/5/29 10:28
 */
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        // boss只关注连接事件
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        Worker worker = new Worker("worker-0");
        while (true) {
            int select = boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 移除
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = ssc.accept();
                    socketChannel.configureBlocking(false);// 设置为非阻塞;
                    System.out.printf("connected:%s\n", socketChannel.getRemoteAddress());
                    System.out.printf("before register:%s\n", socketChannel.getRemoteAddress());
                    worker.register(socketChannel);
//                    socketChannel.register(worker.selector, SelectionKey.OP_READ, null);
                    System.out.printf("after register:%s\n", socketChannel.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        public Selector selector;
        private String name;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
        private volatile boolean start;

        public Worker(String name) {
            this.name = name;
        }

        // 初始化线程和selector
        public void register(SocketChannel sc) {
            if (!start) {
                thread = new Thread(this, name);
                try {
                    selector = Selector.open();
                    System.out.printf("hhh selector:%s\n", selector);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                thread.start();
                // 取反
                start = true;
            }
            // 向队列添加任务
            queue.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();

        }

        @Override
        public void run() {
            while (true) {
                try {
                    // 阻塞
                    System.out.printf("selector:%s\n", selector);
                    selector.select();// 阻塞
                    Runnable poll = queue.poll();
                    if (poll != null) {
                        poll.run();
                    }
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        // 关注可读事件
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel socketChannel = (SocketChannel) key.channel();
                            System.out.printf("before read :%s\n", socketChannel.getRemoteAddress());
                            socketChannel.read(buffer);
                            System.out.printf("after read :%s\n", socketChannel.getRemoteAddress());
                            buffer.flip();
                            System.out.printf("buffer:%s", buffer.toString());
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
